require "Net/drawHandler"
---@class UIDrawChoose : UIBase
UIDrawChoose = UIBase.New(PanelResNames.UIDrawChoose)
local t = UIDrawChoose

local ChooseTab = {}
local Count = 1;
local role_liHui;
local drawWrapper;
local DrawingParent;
local HeroNameText;
local ChooseHeroId;
local JobIcon;
local chooseHero;
local isShowBack
local imageName;
local choose_type
local activity_id

function t.Init(showBack, _choose_type, _activity_id )
    isShowBack = showBack
    choose_type = _choose_type or 1
    activity_id = _activity_id
    UIBase.Init(t)
end

function t:OnCreate()
    if not self.have_init then
        self.have_init = true
        self.Chose = self:GetChild("ok")
        self.backbtn = self:GetChild("back")
        HeroNameText = self:GetChild("cheroname"):GetChild("bigName");
        JobIcon = self:GetChild("cheroname"):GetChild("jobicon"):GetChild("icon");
        self.HeroNameText1 = self:GetChild("bigName")
        self.JobIcon1 = self:GetChild("jobicon"):GetChild("icon");
        self.dynamicList = self:SetDynamicList(self:GetChild("herolist"),self.setData, self, true)
        self.dynamicList1 = self:SetDynamicList(self:GetChild("herolistact"),self.setData, self, true)
        DrawingParent = self:GetChild("herodraw");
        self.iconjinbi = self:GetChild("jinbi")
        self.iconzuanshi = self:GetChild("zuanshi")
        self.jinbinum = self:GetChild("jinbinum")
        self.zuanshinum = self:GetChild("zuanshinum");
        self.HeroBtn = self:GetChild("HeroBtn");
        self.stateCtrl = self:GetController("state")
        self.typeController = self:GetController("Type")
        self.raceController = self:GetController("race")
       
        
        self:SetIcon(self.iconjinbi, logicMgr.ItemManager.getItemConstDatabyModelId(1)["icon"])
        self:RegisterOnClick(self.Chose, self.ChoseBigWin)
        self:RegisterOnClick(self.backbtn, self.ClickClose)
        self:RegisterOnClick(self.HeroBtn, self.ClickHeroBtn)
        if choose_type == 1 then
            self.typeController.selectedIndex = 0;
            self.confCost = decodeJsonStrToTabel(G.dataTable["t_global"]["103"].f_string_value)
             self.confCostItem = logicMgr.ItemManager.getItemConstDatabyModelId(self.confCost[1])
            self:SetIcon(self.iconzuanshi, self.confCostItem["icon"])
            self:GetChild("title22").text = getLanguage("WishFountain_Reset_Des");
            self:RegisterEvent(Config.EventType.WishSetBigReward, self.onClose)
        elseif choose_type == 2 then
            self.typeController.selectedIndex = 1;
            local tb_activitydraw = G.dataTable["t_activitydraw"][tostring(activity_id)] 
            local cfg_draw_item = decodeJsonStrToTabel(tb_activitydraw.f_DrawConsume)   
            self.cost_cfg_item_id1 = cfg_draw_item[1] and cfg_draw_item[1][1] or 0
            self.zuanshinum.text = logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id1)) 
            local cfg_item1 = G.dataTable["t_item"][tostring(self.cost_cfg_item_id1)] or {}
            self.iconzuanshi.url =  "ui://ItemAtlas/" .. tostring(cfg_item1.f_Icon)

            self:GetChild("title22").text = getLanguage("Activitydesc12002");
            self:RegisterEvent(Config.EventType.LimitDrawActivity, self.onClose)
        end
    end
end

-- 
function t:Refresh()
    imageName = nil
    self.jinbinum.text = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD);


    ChooseTab = {}
    if choose_type == 1 then
        self.zuanshinum.text = logicMgr.ItemManager.getItemCountbyModelId(self.confCost[1]);
        local showheroTab = decodeJsonStrToTabel(G.dataTable["t_global"]["99"].f_string_value)
        for i = 1, #showheroTab do
            if logicMgr.HeroManager.isHeroFullyOpen(showheroTab[i]) then
                table.insert(ChooseTab, logicMgr.HeroManager.getHeroDatabyModelId(showheroTab[i]));
            end
        end
    elseif choose_type == 2 then -- 限制抽卡活动英雄选择
        self.zuanshinum.text = tostring(logicMgr.ItemManager.getItemCountbyModelId(tostring(self.cost_cfg_item_id1)))
        --local cfg_item1 = G.dataTable["t_item"][tostring(self.cost_cfg_item_id1)] or {}
        --self.iconzuanshi.url =  "ui://ItemAtlas/" .. tostring(cfg_item1.f_Icon)
        local tb_activitydraw = G.dataTable["t_activitydraw"][tostring(activity_id)]
        local tb_new_hero = tb_activitydraw.f_NewHero
        for _, v in pairs(tb_new_hero) do
            table.insert(ChooseTab, logicMgr.HeroManager.getHeroDatabyModelId(v))
        end
    end

    if ChooseHeroId == nil or ChooseHeroId == 0 then
        ChooseHeroId = tonumber(ChooseTab[1].partnerModelId);
    end
    self.dynamicList.numItems = #ChooseTab;
    self.dynamicList1.numItems = #ChooseTab;
    end
---@param itemobj GComponent
function t:setData(Count, go)
    local itemValue = ChooseTab[Count];
    if itemValue.skinId then
        itemValue.skinId = nil
    end
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectDrawItem);
    if charactor ~= nil then
        --初始英雄信息
        charactor.initData(go, itemValue, true);
    end
    go.onClick:Clear();
    local gou = go:GetController("gou");
    gou.selectedIndex = 0;
    local raceCtrl = go:GetController("topicon");
    raceCtrl.selectedIndex = itemValue.faction
    go.onClick:Add(function()
        self:onClickHero(itemValue, go);
        self:Refresh();

    end);
    if ChooseHeroId ~= nil and itemValue["partnerModelId"] == tostring(ChooseHeroId) then
        gou.selectedIndex = 1;
        self:onClickHero(itemValue, go);
    end
end

function UIDrawChoose:onClickHero(heroData, go)
    local CurHeroConfig = logicMgr.HeroManager.GetHeroConfigbyModelId(heroData["partnerModelId"]);
    ChooseHeroId = CurHeroConfig.f_HeroID;
    local image = logicMgr.HeroManager.GetHeroDrawingPath(heroData["partnerModelId"])
    if imageName == image then
        return;
    end
    imageName = image

    if drawWrapper == nil then
        drawWrapper = GoWrapper.New();
    end

    self.raceController.selectedIndex = heroData.faction

    resMgr:LoadModelPrefab( imageName, function(go)
        if (role_liHui ~= nil) then
            destroyImmediate(role_liHui);
            role_liHui = nil
        end
        role_liHui = newObject(go);
        role_liHui.name = imageName;
        Util.AddAction(role_liHui, "idle1", true, 0.5);

        role_liHui:AddComponent(TCanvas);

        drawWrapper:SetWrapTarget(role_liHui, true)
        local scale, location = HeroManager.GetHeroLocationResize(heroData["partnerModelId"])

        Util.Lua_SetLocalPositionXYZ(role_liHui.transform,location[1],location[2],0)
        Util.Lua_SetLocalScaleXYZ(role_liHui.transform,scale[1]*0.8,scale[2]*0.8,1)
        --DrawingParent:SetXY(540, 760)
        DrawingParent:SetNativeObject(drawWrapper);
    end)
    HeroNameText.text = getLanguage(CurHeroConfig.f_HeroName);
    self.HeroNameText1.text = getLanguage(CurHeroConfig.f_HeroName);
    JobIcon.url = EnumConst.AtlasPath.ICONAtlas .. EnumConst.HeroTypeIcon[CurHeroConfig.f_HeroType]
    self.JobIcon1.url = EnumConst.AtlasPath.ICONAtlas .. EnumConst.HeroTypeIcon[CurHeroConfig.f_HeroType]
end

function t:ChoseBigWin()
    if ChooseHeroId == nil then
        UISysTips.AddMsg(getLanguage("ErrorCode_1749"));
        return;
    end
    if choose_type == 1 then
        drawHandler.GoReqChooseBigRewardMessage(ChooseHeroId)
    elseif choose_type == 2 then
        drawHandler.reqChooseUpHero( activity_id, ChooseHeroId )
        -- drawHandler.ActivityDrawSource.choose_hero_id = ChooseHeroId
        -- FireEvent(Config.EventType.LimitDrawActivity)
    end
end

function t:RefreshItemList()
    self.itemDataList = self:GetDropByItemId(self.itemModelId)
    self.itemList.numItems = #self.itemDataList
end

function t:InitData()

end

function t:OnEnable()
    if isShowBack then
        self.stateCtrl.selectedIndex = 1
    else
        self.stateCtrl.selectedIndex = 0
    end
    if choose_type == 1 then
        ChooseHeroId = drawHandler.WishSource.bigRewardID
    elseif choose_type == 2 then
        ChooseHeroId = drawHandler.ActivityDrawSource and drawHandler.ActivityDrawSource.choose_hero_id -- or 1
    end
    self:Refresh()
end

function t:OnDisable()

end

function t:OnDestroy()
    JobIcon = nil;
    if (role_liHui ~= nil) then
        destroyImmediate(role_liHui);
        role_liHui = nil
    end
    drawWrapper = nil;
    DrawingParent = nil;
    HeroNameText = nil;
    self.have_init = nil
end

function t:ClickHeroBtn()
    if ChooseHeroId == nil or ChooseHeroId == 0 then
        return
    end
    showUI(PanelNames.UIDrawAnimation, ChooseHeroId, nil, false, function()
        closeUI(PanelNames.UIDrawAnimation)
    end, nil, true, true)
end
function t:ClickClose()
    if choose_type == 1 then
        if (drawHandler.WishSource.bigRewardID == 0) then
            closeUI(PanelNames.UIDrawPond)
        else
            closeUI(PanelNames.UIDrawPond)
            --FireEvent(Config.EventType.DrawPondUpdate)
        end
    elseif choose_type == 2 then
        if drawHandler.ActivityDrawSource and drawHandler.ActivityDrawSource.choose_hero_id == 0 then
            closeUI(PanelNames.UIActivityDraw)
        else
            FireEvent(Config.EventType.ActivityDrawHeroChoose)
        end
    end
    closeUI(PanelNames.UIDrawChoose)
end
function t:onClose()
    if choose_type == 1 then
        if drawHandler.WishSource and drawHandler.WishSource.bigRewardID and drawHandler.WishSource.bigRewardID ~= 0 then
            FireEvent(Config.EventType.DrawPondUpdate)
        end
    elseif choose_type == 2 then
        if drawHandler.ActivityDrawSource and drawHandler.ActivityDrawSource.choose_hero_id and drawHandler.ActivityDrawSource.choose_hero_id ~= 0 then
            FireEvent(Config.EventType.ActivityDrawHeroChoose)
        end
    end
    closeUI(PanelResNames.UIDrawChoose)
end

return t
